﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace syc.Store
{
    public partial class 原料出库单 : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {

            string opp3 = (string)Session["OPP3"];
#if DEBUG
            opp3 = ",1,2,3,4,5,6,";
#endif
            if (opp3 == null || opp3 == ",")
            {
                this.Panel2.Visible = false;
                this.Button_Save.Visible = false;
                this.Message.Text = "·权限不足";
                return;
            }
            else
            {
                if (opp3.StartsWith(","))
                {
                    opp3 = opp3.Substring(1);
                }
                if (opp3.EndsWith(","))
                {
                    opp3 = opp3.Substring(0, opp3.Length - 1);
                }
            }


            int id = 0;
            int mainid = 0;
            if (!this.IsPostBack)
            {
                
                this.SqlDataSource2.SelectCommand = "select * from [原料] where [ID] in (" + opp3 + ")";
                this.YuanLiaoID.DataBind();
                this.GuiGe.DataBind();
                this.GangJi.DataBind();
                this.DanWei.DataBind();
                
                //判定是否传递了ID(入库单ID)
                if (Request.QueryString["ID"] != null)
                {
                    int.TryParse(Request.QueryString["ID"], out id);
                }
                if (Request.QueryString["MID"] != null)
                {
                    int.TryParse(Request.QueryString["MID"], out mainid);
                }

                if (id > 0)
                {
                    SqlConnection Conn = new SqlConnection();
                    Conn.ConnectionString = ConfigurationManager.ConnectionStrings["SCMConnectionString1"].ConnectionString;
                    Conn.Open();
                    SqlCommand Cmd = new SqlCommand();
                    Cmd.Connection = Conn;
                    Cmd.CommandText =
@"select 原料出库单.ID,
原料出库单.单据号,
原料出库单.原料ID,
原料出库单.使用单位ID,
原料.品名+'('+原料.钢级+')' as 原料名称,
原料.规格,
原料.单位,
原料出库单.数量,
原料出库单.重量,
原料出库单.主单ID,
原料出库单.剩余数量,
原料出库单.剩余重量,
原料出库单.日期,
原料出库单.库管员 from 原料出库单
inner join 原料 on 原料出库单.原料ID=原料.ID where 原料出库单.[ID]=" + id + " and 原料出库单.原料ID in(" + opp3 + ")";

                    Cmd.CommandType = CommandType.Text;
                    SqlDataReader Reader = Cmd.ExecuteReader();

                    if (Reader.Read())
                    {
                        this.BillID.Text = ((int)Reader["ID"]).ToString();
                        this.MainID.Text = ((int)Reader["主单ID"]).ToString();
                        this.DanHao.Text = ((int)Reader["单据号"]).ToString("0000000");
                        this.YuanLiaoID.Text = ((int)Reader["原料ID"]).ToString();

                        this.FenChang.Text = ((int)Reader["使用单位ID"]).ToString();

                        this.Label_YuanLiao.Text = (string)Reader["原料名称"];
                        this.Label_GuiGe.Text = (string)Reader["规格"];
                        this.Label_DanWei.Text = (string)Reader["单位"];

                        this.YuZhi.Text = ((int)Reader["剩余数量"]).ToString();
                        this.YuZhong.Text = ((decimal)Reader["剩余重量"]).ToString();

                        this.ZhiShu.Text = ((int)Reader["数量"] + (int)Reader["剩余数量"]).ToString();
                        this.ZhongLiang.Text = ((decimal)Reader["重量"] + (decimal)Reader["剩余重量"]).ToString();
                        this.Date1.Text = ((DateTime)Reader["日期"]).ToLongDateString();

                        Reader.Close();
                        Cmd.CommandText = "select 数量,重量,单价 from 原料库存 where 数量<0 and 单据ID=" + id;
                        Reader = Cmd.ExecuteReader();
                        int i, j;
                        string s;
                        char[] cs;
                        for (i = 1; i <= 5; i++)
                        {
                            if (Reader.Read())
                            {
                                ((TextBox)this.FindControl("ShuLiang" + i)).Text = (-(int)Reader["数量"]).ToString();
                                ((TextBox)this.FindControl("ZhongLiang" + i)).Text = (-(decimal)Reader["重量"]).ToString();
                                s = ((decimal)Reader["单价"]).ToString();

                                ((TextBox)this.FindControl("DanJia" + i)).Text = s;
                                cs = s.ToCharArray();
                                for (j = s.Length - 1; j >= 0; j--)
                                {
                                    if (cs[j] != '0')
                                    {
                                        if (cs[j] == '.')
                                        {
                                            j--;
                                        }
                                        ((TextBox)this.FindControl("DanJia" + i)).Text = s.Substring(0, j + 1);
                                        break;
                                    }
                                }
                                ((Label)this.FindControl("JinE" + i)).Text = ((-(decimal)Reader["重量"]) * ((decimal)Reader["单价"])).ToString(".00");
                            }
                            else
                            {
                                break;
                            }
                        }
                        this.Panel3.Visible = false;
                    }
                    else
                    {
                        this.Message.Text = "·权限不足或出库单不存在";
                        this.Panel2.Visible = false;
                        this.Button_Save.Visible = false;
                    }

                    Reader.Close();
                    Conn.Close();
                    Reader.Dispose();
                    Cmd.Dispose();
                    Conn.Dispose();
                    return;
                }
                else if (mainid > 0)
                {
                    SqlConnection Conn = new SqlConnection();
                    Conn.ConnectionString = ConfigurationManager.ConnectionStrings["SCMConnectionString1"].ConnectionString;
                    Conn.Open();
                    SqlCommand Cmd = new SqlCommand();
                    Cmd.Connection = Conn;
                    Cmd.CommandText = "select 原料ID,使用单位ID,存储区域,剩余数量,剩余重量 from 原料出库单 where id=" + mainid + " and 原料ID in(" + opp3 + ")";

                    Cmd.CommandType = CommandType.Text;
                    SqlDataReader Reader = Cmd.ExecuteReader();

                    if (Reader.Read())
                    {
                        this.MainID.Text = mainid.ToString();
                        this.YuanLiaoID.Text = ((int)Reader["原料ID"]).ToString();
                        this.FenChang.Text = ((int)Reader["使用单位ID"]).ToString();
                        ListItem li = new ListItem();
                        li.Text = ((int)Reader["存储区域"]).ToString();
                        this.KuQu.Items.Add(li);
                        this.ZhiShu.Text = ((int)Reader["剩余数量"]).ToString();
                        this.ZhongLiang.Text = ((decimal)Reader["剩余重量"]).ToString();
                        this.ShuLiang1.Text = this.ZhiShu.Text;
                        this.ZhongLiang1.Text = this.ZhongLiang.Text;

                        this.Label_YuanLiao.Text = this.YuanLiaoID.SelectedItem.Text + "(" + this.GangJi.Items[this.YuanLiaoID.SelectedIndex].Text + ")";
                        this.Label_GuiGe.Text = this.GuiGe.Items[this.YuanLiaoID.SelectedIndex].Text;
                        this.Label_DanWei.Text = this.DanWei.Items[this.YuanLiaoID.SelectedIndex].Text;
                    }

                    Reader.Close();
                    Conn.Close();
                    Reader.Dispose();
                    Cmd.Dispose();
                    Conn.Dispose();
                    this.Date1.Text = DateTime.Today.ToLongDateString();
                    this.Panel3.Visible = false;
                    return;
                }
                else
                {
                    YuanLiaoID_SelectedIndexChanged(null, null);
                    this.Date1.Text = DateTime.Today.ToLongDateString();
                }
            }
        }

        private bool CheckInput()
        {
            DateTime d;
            if (!DateTime.TryParse(this.Date1.Text, out d))
            {
                this.Message.Text = "·日期输入有误";
                return false;
            }
            int n;
            if (!int.TryParse(this.DanHao.Text, out n))
            {
                this.Message.Text = "·单据号（No.）输入有误";
                return false;
            }
            else if (n < 1)
            {
                this.Message.Text = "·单据号（No.）输入有误";
                return false;
            }
            int i;
            int shuliang, zs = 0;
            decimal zhongloang, zz = 0;
            decimal danjia;

            for (i = 1; i <= 5; i++)
            {
                ((Label)this.FindControl("JinE" + i)).Text = "";
                if (((TextBox)this.FindControl("ShuLiang" + i)).Text.Trim() != ""
                    || ((TextBox)this.FindControl("ZhongLiang" + i)).Text.Trim() != ""
                    || ((TextBox)this.FindControl("DanJia" + i)).Text.Trim() != ""
                    )
                {
                    if (!int.TryParse(((TextBox)this.FindControl("ShuLiang" + i)).Text, out shuliang))
                    {
                        this.Message.Text = "·第" + i + "行“数量”输入有误";
                        return false;
                    }
                    if (!decimal.TryParse(((TextBox)this.FindControl("ZhongLiang" + i)).Text, out zhongloang))
                    {
                        this.Message.Text = "·第" + i + "行“重量”输入有误";
                        return false;
                    }
                    if (!decimal.TryParse(((TextBox)this.FindControl("DanJia" + i)).Text, out danjia))
                    {
                        this.Message.Text = "·第" + i + "行“单价”输入有误";
                        return false;
                    }
                    if (shuliang <= 0 || zhongloang <= 0 || danjia <= 0)
                    {
                        this.Message.Text = "·“数量”、“重量”、“单价”需为正数";
                        return false;
                    }
                    ((Label)this.FindControl("JinE" + i)).Text = (zhongloang * danjia).ToString(".00");
                    zs += shuliang;
                    zz += zhongloang;
                }

            }

            int MaxZhi = int.Parse(this.ZhiShu.Text);
            decimal MaxZhong = decimal.Parse(this.ZhongLiang.Text);

            this.YuZhi.Text = (MaxZhi - zs).ToString();
            this.YuZhong.Text = (MaxZhong - zz).ToString();


            int billid = -1;
            int.TryParse(this.BillID.Text, out billid);
            int mainid = -1;
            int.TryParse(this.MainID.Text, out mainid);
            if (billid > 0 && mainid > 0)
            {
                if (MaxZhi != zs)
                {
                    this.Message.Text = "·录入数量不等于总数";
                    return false;
                }
                else if (MaxZhong != zz)
                {
                    this.Message.Text = "·录入重量不等于总数";
                    return false;
                }
            }
            else
            {
                if (MaxZhi < zs)
                {
                    this.Message.Text = "·录入数量大于总数";
                    return false;
                }
                else if (MaxZhong < zz)
                {
                    this.Message.Text = "·录入重量大于总数";
                    return false;
                }
            }
            this.Message.Text = "·录入数据校验成功";
            return true;
        }

        protected void Button_Save_Click(object sender, EventArgs e)
        {
            if (this.CheckInput())
            {
                SqlConnection Conn = new SqlConnection();
                Conn.ConnectionString = ConfigurationManager.ConnectionStrings["SCMConnectionString1"].ConnectionString;
                Conn.Open();
                SqlTransaction Tran = Conn.BeginTransaction();
                SqlCommand Cmd = new SqlCommand();
                Cmd.Connection = Conn;
                Cmd.Transaction = Tran;
                int billid = -1;
                int.TryParse(this.BillID.Text, out billid);

                int mainid = 0;
                int.TryParse(this.MainID.Text, out mainid);

                DateTime d = DateTime.Parse(this.Date1.Text);
                int n = int.Parse(this.DanHao.Text);
                int i;
                string op = (string)this.Session["OperatorName"];
                if (op == null)
                {
                    op = "";
                }
                try
                {
                    Cmd.CommandText = "YuanLiao_Out_Bill";
                    Cmd.CommandType = CommandType.StoredProcedure;

                    int zs=int.Parse(this.ZhiShu.Text);//总支数
                    int ys=int.Parse(this.YuZhi.Text);//剩余支数
                    decimal zz = decimal.Parse(this.ZhongLiang.Text);//总重
                    decimal yz = decimal.Parse(this.YuZhong.Text);//剩余重量
                    

                    Cmd.Parameters.Add(new SqlParameter("@单据号", SqlDbType.Int, 4, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, n));
                    Cmd.Parameters.Add(new SqlParameter("@原料ID", SqlDbType.Int, 4, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, int.Parse(this.YuanLiaoID.Text)));
                    Cmd.Parameters.Add(new SqlParameter("@使用单位ID", SqlDbType.Int, 4, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, int.Parse(this.FenChang.Text)));
                    int kq = 0;
                    int.TryParse(this.KuQu.Text, out kq);
                    Cmd.Parameters.Add(new SqlParameter("@存储区域", SqlDbType.Int, 4, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, kq));

                    Cmd.Parameters.Add(new SqlParameter("@数量", SqlDbType.Int, 4, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, zs-ys));
                    Cmd.Parameters.Add(new SqlParameter("@重量", SqlDbType.Decimal, 9, ParameterDirection.Input, true, 18, 3, "", DataRowVersion.Proposed, zz-yz));

                    Cmd.Parameters.Add(new SqlParameter("@主单ID", SqlDbType.Int, 4, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, mainid));
                    Cmd.Parameters.Add(new SqlParameter("@剩余数量", SqlDbType.Int, 4, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, ys));
                    Cmd.Parameters.Add(new SqlParameter("@剩余重量", SqlDbType.Decimal, 9, ParameterDirection.Input, true, 18, 3, "", DataRowVersion.Proposed, yz));

                    Cmd.Parameters.Add(new SqlParameter("@日期", SqlDbType.Date, 3, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, d));
                    Cmd.Parameters.Add(new SqlParameter("@库管员", SqlDbType.NChar, 20, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, op));
                    Cmd.Parameters.Add(new SqlParameter("@备注", SqlDbType.NVarChar, 100, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, ""));
                    Cmd.Parameters.Add(new SqlParameter("@BillID", SqlDbType.Int, 4, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, billid));
                    Cmd.Parameters.Add(new SqlParameter("@ID", SqlDbType.Int, 4, ParameterDirection.Output, true, 0, 0, "", DataRowVersion.Proposed, ""));

                    Cmd.ExecuteNonQuery();

                    billid = (int)Cmd.Parameters["@ID"].Value;
                    this.BillID.Text = billid.ToString();
                    if (billid > 0)
                    {
                        Cmd.CommandText = "YuanLiao_In";
                        Cmd.Parameters.Clear();
                        Cmd.Parameters.Add(new SqlParameter("@单据ID", SqlDbType.Int, 4, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, billid));
                        Cmd.Parameters.Add(new SqlParameter("@原料ID", SqlDbType.Int, 4, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, int.Parse(this.YuanLiaoID.Text)));
                        Cmd.Parameters.Add(new SqlParameter("@批次", SqlDbType.VarChar, 20, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, ""));
                        Cmd.Parameters.Add(new SqlParameter("@数量", SqlDbType.Int, 4, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, 0));
                        Cmd.Parameters.Add(new SqlParameter("@重量", SqlDbType.Decimal, 9, ParameterDirection.Input, true, 18, 3, "", DataRowVersion.Proposed, 0));
                        Cmd.Parameters.Add(new SqlParameter("@单价", SqlDbType.Decimal, 13, ParameterDirection.Input, true, 27, 10, "", DataRowVersion.Proposed, 0));
                        Cmd.Parameters.Add(new SqlParameter("@日期", SqlDbType.Date, 3, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, d));
                        for (i = 1; i <= 5; i++)
                        {

                            if (((TextBox)this.FindControl("ShuLiang" + i)).Text.Trim() != ""
                                && ((TextBox)this.FindControl("ZhongLiang" + i)).Text.Trim() != ""
                                && ((TextBox)this.FindControl("DanJia" + i)).Text.Trim() != "")
                            {
                                Cmd.Parameters["@数量"].Value = -int.Parse(((TextBox)this.FindControl("ShuLiang" + i)).Text);
                                Cmd.Parameters["@重量"].Value = -decimal.Parse(((TextBox)this.FindControl("ZhongLiang" + i)).Text);
                                Cmd.Parameters["@单价"].Value = decimal.Parse(((TextBox)this.FindControl("DanJia" + i)).Text);
                                Cmd.ExecuteNonQuery();
                            }
                        }
                        this.Message.Text += "·保存成功";
                        this.Panel3.Visible = false;
                    }
                    else
                    {
                        this.Message.Text = "·单价编号(No.)已经存在";
                    }
                    Tran.Commit();
                }
                catch (Exception err)
                {
                    Tran.Rollback();
                    this.Message.Text = err.Message;
                }
                Cmd.Dispose();
                Tran.Dispose();
                Conn.Close();
                Conn.Dispose();
            }
        }

        protected void Button_Check_Click(object sender, EventArgs e)
        {
            this.CheckInput();
        }

        protected void FenChang_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.SqlDataSource1.SelectCommand = "select distinct 区域 from 管材到货明细 where 状态=1 and 使用单位=" + this.FenChang.Text +" and 管材ID="+this.YuanLiaoID.Text;
            this.KuQu.DataBind();
            KuQu_SelectedIndexChanged(null, null);
            
        }

        protected void KuQu_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (KuQu.Items.Count > 0)
            {
                SqlConnection Conn = new SqlConnection();
                Conn.ConnectionString = ConfigurationManager.ConnectionStrings["SCMConnectionString1"].ConnectionString;
                Conn.Open();
                SqlCommand Cmd = new SqlCommand();
                Cmd.Connection = Conn;
                Cmd.CommandText = "select sum(支数) as 支数,sum(磅重) as 重量 from 管材到货明细 where 使用单位=" + this.FenChang.Text + " and 管材ID=" + this.YuanLiaoID.Text + " and 区域=" + this.KuQu.Text ;
                Cmd.CommandType = CommandType.Text;
                SqlDataReader Reader = Cmd.ExecuteReader();
                if (Reader.Read())
                {
                    this.ZhiShu.Text = ((int)Reader["支数"]).ToString();
                    this.ZhongLiang.Text = ((decimal)Reader["重量"]).ToString();
                    this.ShuLiang1.Text = this.ZhiShu.Text;
                    this.ZhongLiang1.Text = this.ZhongLiang.Text;
                }
                else
                {
                    this.ZhiShu.Text = "0";
                    this.ZhongLiang.Text = "0";
                    this.ShuLiang1.Text = "";
                    this.ZhongLiang1.Text = "";
                }
                Reader.Close();
                Conn.Close();
                Reader.Dispose();
                Cmd.Dispose();
                Conn.Dispose();
            }
            else
            {
                this.ZhiShu.Text = "0";
                this.ZhongLiang.Text = "0";
                this.ShuLiang1.Text = "";
                this.ZhongLiang1.Text = "";
            }
        }

        protected void YuanLiaoID_SelectedIndexChanged(object sender, EventArgs e)
        {
            FenChang_SelectedIndexChanged(null, null);
            this.Label_YuanLiao.Text = this.YuanLiaoID.SelectedItem.Text + "(" + this.GangJi.Items[this.YuanLiaoID.SelectedIndex].Text + ")";
            this.Label_GuiGe.Text = this.GuiGe.Items[this.YuanLiaoID.SelectedIndex].Text;
            this.Label_DanWei.Text =  this.DanWei.Items[this.YuanLiaoID.SelectedIndex].Text;
        }

    }
}
